<template>
  <a-layout class="create-post-layout">
    <a-layout-content class="content">
      <div class="create-post-container">
        <!-- 返回按钮 -->
        <div class="back-btn">
          <a-button @click="goBack">返回</a-button>
        </div>

        <h2>创建新帖子</h2>

        <!-- 表单部分 -->
        <a-form
          @submit.prevent="handleSubmit"
          class="create-post-form"
        >
          <!-- 帖子标题 -->
          <a-form-item
            label="标题"
          >
            <a-textarea
              v-model="formData.title"
              placeholder="请输入帖子标题"
              style="height: 30px"
            />
          </a-form-item>

          <!-- 帖子内容 -->
          <a-form-item
            label="内容"
          >
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="formData.content"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
              />
            </div>
          </a-form-item>

          <!-- 提交按钮 -->
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 0 auto;
              width: 600px;
            "
          >
            <a-form-item>
              <a-button type="primary" html-type="submit">提交</a-button>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { onBeforeUnmount, shallowRef, ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router"; // 引入 useRoute 获取路由参数
import { Form, Input, Button, Select } from "ant-design-vue";
import { useStore } from "vuex"; // 引入 useStore 来访问 Vuex
import request from "@/utils/request";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ElMessage } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  name: "CreatePost",
  components: {
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    ATextArea: Input.TextArea,
    AButton: Button,
    ASelect: Select,
    ASelectOption: Select.Option,
    Editor,
    Toolbar,
  },
  setup() {
    const store = useStore(); // 使用 useStore 获取 Vuex store
    const router = useRouter(); // 获取路由实例
    const route = useRoute(); // 获取路由参数
    const formData = ref({
      title: "",
      content: "",
      userName: "",
      userId: "",
    });

    // 获取当前登录用户信息
    onMounted(() => {
      formData.value.userName = store.state.user.user.username; // 从 Vuex 获取用户名
      formData.value.userId = store.state.user.user.id; // 从 Vuex 获取用户ID

      // 如果是编辑模式，从路由传参中获取文章信息并填充表单
      if (route.query.mode === "edit") {
        formData.value.title = route.query.title;
        formData.value.content = route.query.content;
        formData.value.id = route.query.id; // 传递的文章 ID
      }
    });

    // 提交表单的处理函数
    const handleSubmit = () => {
      if (formData.value.title === "" || formData.value.content === "") {
        window.alert("标题和内容不能为空！");
        return;
      }

      // 编辑时使用 PUT 请求更新文章，创建时使用 POST 请求创建文章
      if (formData.value.id) {
        // 编辑模式
        request
          .put("/forum/update/", formData.value)
          .then((response) => {
            ElMessage.success("帖子更新成功！");
            goBack();
          })
          .catch((error) => {
            ElMessage.error("编辑帖子失败");
          });
      } else {
        // 创建模式
        request
          .post("/forum/add", formData.value)
          .then((response) => {
            ElMessage.success("帖子创建成功！");
            goBack();
          })
          .catch((error) => {
            ElMessage.error("创建帖子失败");
          });
      }
    };

    const goBack = () => {
      // 如果有上一页，直接返回上一页
      if (window.history.length > 1) {
        router.go(-1);
      } else {
        // 否则返回到帖子列表页
        router.push("/forum");
      }
    };

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    const toolbarConfig = {};
    const editorConfig = { placeholder: "请输入内容..." };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    return {
      formData,
      handleSubmit,
      goBack,
      editorRef,
      toolbarConfig,
      editorConfig,
      handleCreated,
    };
  },
};
</script>

<style scoped>
.create-post-layout {
  background-color: #f5f5f5;
  padding: 30px 0;
}

.create-post-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 1000px;
  margin: 0 auto;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
}

.create-post-form .ant-btn {
  width: 600px;
}
</style>
